import React, { useState, useEffect } from 'react';
import { Table, Button, Card, Modal, Form, Input, message, Popconfirm, Space, Typography } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Category } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';
import { mockCategories } from '../../services/mockData';

const { Title } = Typography;

const CategoryManagement: React.FC = () => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    const savedCategories = Storage.get<Category[]>(STORAGE_KEYS.CATEGORIES);
    setCategories(savedCategories || mockCategories);
  };

  const saveCategories = (newCategories: Category[]) => {
    Storage.set(STORAGE_KEYS.CATEGORIES, newCategories);
    setCategories(newCategories);
  };

  const handleAdd = () => {
    setEditingCategory(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (category: Category) => {
    setEditingCategory(category);
    form.setFieldsValue(category);
    setModalVisible(true);
  };

  const handleDelete = (categoryId: string) => {
    const newCategories = categories.filter(c => c.id !== categoryId);
    saveCategories(newCategories);
    message.success('删除成功');
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      if (editingCategory) {
        // 编辑
        const newCategories = categories.map(c => 
          c.id === editingCategory.id 
            ? { ...values, id: editingCategory.id }
            : c
        );
        saveCategories(newCategories);
        message.success('更新成功');
      } else {
        // 新增
        const newCategory: Category = {
          ...values,
          id: Date.now().toString(),
        };
        saveCategories([...categories, newCategory]);
        message.success('添加成功');
      }
      
      setModalVisible(false);
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '分类图标',
      dataIndex: 'icon',
      key: 'icon',
      width: 80,
      render: (icon: string) => (
        <span style={{ fontSize: 24 }}>{icon}</span>
      ),
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '分类ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: Category) => (
        <Space size="small">
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个分类吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <Title level={2}>分类管理</Title>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          添加分类
        </Button>
      </div>

      <Card>
        <Table
          columns={columns}
          dataSource={categories}
          rowKey="id"
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <Modal
        title={editingCategory ? '编辑分类' : '添加分类'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            name="icon"
            label="分类图标"
            rules={[{ required: true, message: '请输入分类图标' }]}
          >
            <Input placeholder="请输入分类图标（emoji）" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CategoryManagement;
